package com.cjy.utils;

import com.cjy.handler.CustomRequestWrapper;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Cheng JiYe
 * @description: web服务端的工具类
 * @date 2020/11/10 8:55
 */
public class WebUtil {
    /**
     * 获取客户端的IP地址
     *
     * @param request 当前请求
     * @return IP地址
     */
    public static String getIP(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = ip.indexOf(",");
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        }
        ip = request.getHeader("X-Real-IP");
        if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            return ip;
        }
        return request.getRemoteAddr();
    }

    /**
     * 获取当前请求的域名Url
     *
     * @param request 请求
     * @return 域名Url
     */
    public static String getDomainUrl(HttpServletRequest request) {
        String requestUrl = "https" //当前链接使用的协议
                + "://" + request.getServerName();//服务器地址
        return requestUrl;
    }

    /**
     * 获取请求头信息
     *
     * @param request 请求
     * @return 请求头信息
     */
    public static Map<String, String> getHeadersInfo(HttpServletRequest request) {
        Map<String, String> map = new HashMap<>(100);
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            map.put(key, value);
        }
        return map;
    }

    /**
     * 获取当前请求的域名Url
     *
     * @param request 请求
     * @return 域名Url
     */
    public static String getCurrentUrl(HttpServletRequest request) {
        String requestUrl = "https" //当前链接使用的协议
                + "://" + request.getServerName();//服务器地址
        if (request.getServerPort() != 80 && request.getServerPort() != 443) {
            requestUrl += ":" + request.getServerPort(); //端口号
        }
        requestUrl += request.getContextPath(); //应用名称，如果应用名称为
        requestUrl += request.getServletPath(); //请求的相对url
        if (StringUtils.isNotEmpty(request.getQueryString())) {
            requestUrl += "?" + request.getQueryString(); //请求参数
        }
        return requestUrl;
    }

    public static void write(HttpServletResponse response, String str) throws IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.print(str);
        out.flush();
        out.close();
    }

    public static void writeJson(HttpServletResponse response, String str) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(str);
    }

    /**
     * 把请求参数设置到map中
     *
     * @param request
     * @return
     */
    public static Map<String, String> getRequestParams(HttpServletRequest request) {
        Map<String, String> params = new HashMap<>(100);
        Map<String, String[]> paramMap = request.getParameterMap();
        for (String paramKey : paramMap.keySet()) {
            String[] arr = paramMap.get(paramKey);
            if (arr != null) {
                String val = "";
                for (String s : arr) {
                    val += s;
                }
                params.put(paramKey, val);
            }
        }
        return params;
    }

    /**
     * 把请求body设置到map中
     *
     * @param customRequestWrapper
     * @return
     */
    public static Map<String, String> getRequestBody(CustomRequestWrapper customRequestWrapper) {
        Map<String, String> params = new HashMap<>(100);
        byte[] body = customRequestWrapper.getBody();
        return params;
    }

    /**
     * 获取请求Body
     *
     * @param request
     * @return
     */
    public static String getBodyString(ServletRequest request) {
        StringBuilder sb = new StringBuilder();
        InputStream inputStream = null;
        BufferedReader reader = null;
        try {
            inputStream = request.getInputStream();
            reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
            String line = "";
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }
}
